package com.nlx.notes.module.core.handler;

import com.nlx.notes.module.bean.vo.PageResultVo;
import com.nlx.notes.module.bean.vo.ResultVO;
import com.nlx.notes.module.core.util.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {

//    @ExceptionHandler(Exception.class)
//    public ResultVO exception(Exception e) {
//        log.error("全局异常信息 ex={}", e.getMessage(), e);
//        return ResultVO.error("failed");
//    }


    // 判断是否支持拦截当前返回值
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        // 如果返回类型已经是 ResultVO，则不需要拦截
        return true;
    }

    // 处理返回值
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(null == body){
            return ResultVO.success(null);
        }
        // 如果返回的已经是 ResultVO 类型，直接返回
        if (body instanceof ResultVO) {
            return body;
        }
        if(body instanceof PageResultVo<?>){
            return body;
        }

        if (body instanceof String) {
            return JSONUtils.toString(ResultVO.success(body));
        }

        // 否则包装成统一结构
        return ResultVO.success(body);
    }



}
